package com.zzz.KeyValueTextInputFormat;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

import java.io.IOException;

public class KeyValueMain{

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Configuration conf = new Configuration();
        conf.set("key.value.separator.in.input.line","@zolen@");
        Job job = Job.getInstance(conf, "KeyValueInputFormat");

        job.setJarByClass(KeyValueMain.class);

        job.setInputFormatClass(KeyValueTextInputFormat.class);
        KeyValueTextInputFormat.addInputPath(job,new Path("file:///E:\\大数据\\数据"));

        job.setMapperClass(KeyValueMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        job.setReducerClass(KeyValueReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        job.setOutputFormatClass(TextOutputFormat.class);
        TextOutputFormat.setOutputPath(job,new Path("file:///E:\\大数据\\数据\\out"));

        boolean b = job.waitForCompletion(true);
        System.exit(0);

    }


    /**
     * key 是 string类型
     * val 是 string类型
     */
    public static class KeyValueMapper extends Mapper<Text, Text,Text, LongWritable> {
        @Override
        protected void map(Text key, Text value, Context context) throws IOException, InterruptedException {
            LongWritable outValue = new LongWritable(1);
            context.write(key,outValue);
        }
    }

    public static class KeyValueReducer extends Reducer<Text, LongWritable,Text,LongWritable> {
        @Override
        protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
            long result = 0L;
            for (LongWritable value : values){
                result += value.get();
            }
            context.write(key,new LongWritable(result));
        }
    }
}
